<template>
  <div class="student-container">
    <el-card>
      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="关键词">
          <el-input v-model="searchForm.keyword" placeholder="学号/姓名" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="院系">
          <el-select v-model="searchForm.deptId" placeholder="请选择院系" clearable style="width: 150px">
            <el-option
              v-for="dept in deptList"
              :key="dept.id"
              :label="dept.deptName"
              :value="dept.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="班级">
          <el-select v-model="searchForm.classId" placeholder="请选择班级" clearable style="width: 150px">
            <el-option
              v-for="cls in classList"
              :key="cls.id"
              :label="cls.className"
              :value="cls.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="学籍状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable style="width: 120px">
            <el-option label="在籍" :value="1" />
            <el-option label="休学" :value="2" />
            <el-option label="毕业" :value="3" />
            <el-option label="退学" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="handleAdd" :icon="Plus">新增学生</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table :data="tableData" border stripe v-loading="loading">
        <el-table-column prop="studentNo" label="学号" width="120" />
        <el-table-column prop="realName" label="姓名" width="100" />
        <el-table-column prop="genderText" label="性别" width="60" />
        <el-table-column prop="deptName" label="院系" />
        <el-table-column prop="className" label="班级" />
        <el-table-column prop="phone" label="联系电话" width="120" />
        <el-table-column prop="statusText" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ row.statusText }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)" v-if="isAdmin">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="90px">
        <!-- 基本信息 -->
        <el-divider content-position="left">
          <el-icon><User /></el-icon>
          <span style="margin-left: 8px;">基本信息</span>
        </el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学号" prop="studentNo">
              <el-input 
                v-model="formData.studentNo" 
                :disabled="!!formData.id" 
                placeholder="请输入学号"
                clearable
              >
                <template #prefix>
                  <el-icon><Postcard /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="realName">
              <el-input 
                v-model="formData.realName" 
                placeholder="请输入姓名"
                clearable
              >
                <template #prefix>
                  <el-icon><User /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="formData.gender">
                <el-radio :label="1">
                  <el-icon><Male /></el-icon> 男
                </el-radio>
                <el-radio :label="2">
                  <el-icon><Female /></el-icon> 女
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生日期" prop="birthday">
              <el-date-picker
                v-model="formData.birthday"
                type="date"
                placeholder="选择出生日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              >
                <template #prefix>
                  <el-icon><Calendar /></el-icon>
                </template>
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 学籍信息 -->
        <el-divider content-position="left">
          <el-icon><School /></el-icon>
          <span style="margin-left: 8px;">学籍信息</span>
        </el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="院系" prop="deptId">
              <el-select 
                v-model="formData.deptId" 
                placeholder="请选择院系" 
                style="width: 100%" 
                @change="handleDeptChange"
                clearable
                filterable
              >
                <template #prefix>
                  <el-icon><OfficeBuilding /></el-icon>
                </template>
                <el-option
                  v-for="dept in deptList"
                  :key="dept.id"
                  :label="dept.deptName"
                  :value="dept.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班级" prop="classId">
              <el-select 
                v-model="formData.classId" 
                placeholder="请选择班级" 
                style="width: 100%"
                clearable
                filterable
              >
                <template #prefix>
                  <el-icon><School /></el-icon>
                </template>
                <el-option
                  v-for="cls in filteredClassList"
                  :key="cls.id"
                  :label="cls.className"
                  :value="cls.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入学日期" prop="enrollDate">
              <el-date-picker
                v-model="formData.enrollDate"
                type="date"
                placeholder="选择入学日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              >
                <template #prefix>
                  <el-icon><Calendar /></el-icon>
                </template>
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学籍状态" prop="status">
              <el-select v-model="formData.status" placeholder="请选择状态" style="width: 100%">
                <template #prefix>
                  <el-icon><Flag /></el-icon>
                </template>
                <el-option label="在籍" :value="1">
                  <el-tag type="success" size="small">在籍</el-tag>
                </el-option>
                <el-option label="休学" :value="2">
                  <el-tag type="warning" size="small">休学</el-tag>
                </el-option>
                <el-option label="毕业" :value="3">
                  <el-tag type="info" size="small">毕业</el-tag>
                </el-option>
                <el-option label="退学" :value="4">
                  <el-tag type="danger" size="small">退学</el-tag>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 联系方式 -->
        <el-divider content-position="left">
          <el-icon><Phone /></el-icon>
          <span style="margin-left: 8px;">联系方式</span>
        </el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input 
                v-model="formData.phone" 
                placeholder="请输入手机号码"
                maxlength="11"
                clearable
              >
                <template #prefix>
                  <el-icon><Phone /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="家庭住址">
              <el-input 
                v-model="formData.address" 
                placeholder="请输入家庭住址"
                clearable
              >
                <template #prefix>
                  <el-icon><Location /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 备注信息 -->
        <el-divider content-position="left">
          <el-icon><Document /></el-icon>
          <span style="margin-left: 8px;">备注信息</span>
        </el-divider>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="formData.remark" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入备注信息（选填）"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false" size="large">
            <el-icon><Close /></el-icon>
            取消
          </el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading" size="large">
            <el-icon><Check /></el-icon>
            {{ formData.id ? '保存' : '确定' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'
import { 
  Search, 
  Plus, 
  User, 
  Male, 
  Female, 
  Calendar, 
  School, 
  OfficeBuilding, 
  Phone, 
  Location, 
  Document, 
  Postcard, 
  Flag, 
  Check, 
  Close 
} from '@element-plus/icons-vue'
import { getStudentPage, addStudent, updateStudent, deleteStudent } from '@/api/student'
import { getDeptList } from '@/api/dept'
import { getClassList } from '@/api/class'
import { useUserStore } from '@/store/user'
import type { Student, Dept, Classes } from '@/types'

const userStore = useUserStore()
const isAdmin = computed(() => userStore.userInfo?.roleCode === 'admin')

const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('新增学生')
const formRef = ref<FormInstance>()

const searchForm = reactive({
  keyword: '',
  status: undefined as number | undefined,
  deptId: undefined as number | undefined,
  classId: undefined as number | undefined
})

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

const tableData = ref<Student[]>([])
const deptList = ref<Dept[]>([])
const classList = ref<Classes[]>([])

// 根据选择的院系过滤班级列表
const filteredClassList = computed(() => {
  if (!formData.deptId || formData.deptId === 0) {
    return classList.value
  }
  // 使用宽松比较，避免类型不匹配
  return classList.value.filter(cls => cls.deptId == formData.deptId)
})

const formData = reactive<Student>({
  id: undefined,
  studentNo: '',
  realName: '',
  gender: 1,
  birthday: '',
  deptId: undefined as any,
  classId: undefined as any,
  enrollDate: '',
  phone: '',
  address: '',
  status: 1,
  remark: ''
})

// 手机号验证规则
const validatePhone = (_rule: any, value: any, callback: any) => {
  if (!value) {
    callback()
  } else {
    const phoneReg = /^1[3-9]\d{9}$/
    if (!phoneReg.test(value)) {
      callback(new Error('请输入正确的手机号码'))
    } else {
      callback()
    }
  }
}

const formRules = {
  studentNo: [
    { required: true, message: '请输入学号', trigger: 'blur' },
    { min: 6, max: 20, message: '学号长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  deptId: [
    { required: true, message: '请选择院系', trigger: 'change' }
  ],
  classId: [
    { required: true, message: '请选择班级', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择学籍状态', trigger: 'change' }
  ],
  phone: [
    { validator: validatePhone, trigger: 'blur' }
  ]
}

// 获取院系列表
const fetchDeptList = async () => {
  try {
    const data = await getDeptList()
    deptList.value = data
  } catch (error) {
    console.error('获取院系列表失败', error)
  }
}

// 获取班级列表
const fetchClassList = async () => {
  try {
    const data = await getClassList()
    classList.value = data
  } catch (error) {
    console.error('获取班级列表失败', error)
  }
}

// 院系改变时，清空班级选择
const handleDeptChange = () => {
  formData.classId = undefined as any
}

// 获取列表
const fetchData = async () => {
  loading.value = true
  try {
    const data = await getStudentPage({
      current: pagination.current,
      size: pagination.size,
      ...searchForm
    })
    tableData.value = data.records
    pagination.total = data.total
  } catch (error) {
    console.error('获取学生列表失败', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchData()
}

// 重置
const handleReset = () => {
  searchForm.keyword = ''
  searchForm.status = undefined
  searchForm.deptId = undefined
  searchForm.classId = undefined
  pagination.current = 1
  fetchData()
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增学生'
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: Student) => {
  dialogTitle.value = '编辑学生'
  
  // 复制数据到表单，确保数据类型正确
  Object.assign(formData, {
    ...row,
    // 确保是 number 类型，处理各种情况
    deptId: row.deptId && row.deptId !== 0 ? Number(row.deptId) : undefined,
    classId: row.classId && row.classId !== 0 ? Number(row.classId) : undefined
  })
  
  dialogVisible.value = true
}

// 删除
const handleDelete = (row: Student) => {
  ElMessageBox.confirm(`确定要删除学生【${row.realName}】吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteStudent(row.id!)
      ElMessage.success('删除成功')
      fetchData()
    } catch (error) {
      console.error('删除失败', error)
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        const api = formData.id ? updateStudent : addStudent
        await api(formData)
        ElMessage.success(formData.id ? '编辑成功' : '新增成功')
        dialogVisible.value = false
        fetchData()
      } catch (error) {
        console.error('提交失败', error)
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 关闭对话框
const handleDialogClose = () => {
  formRef.value?.resetFields()
  Object.assign(formData, {
    id: undefined,
    studentNo: '',
    realName: '',
    gender: 1,
    birthday: '',
    deptId: undefined,
    classId: undefined,
    enrollDate: '',
    phone: '',
    address: '',
    status: 1,
    remark: ''
  })
}

// 分页
const handleSizeChange = () => {
  fetchData()
}

const handleCurrentChange = () => {
  fetchData()
}

// 状态标签类型
const getStatusType = (status: number) => {
  const typeMap: Record<number, any> = {
    1: 'success',
    2: 'warning',
    3: 'info',
    4: 'danger'
  }
  return typeMap[status] || 'info'
}

onMounted(() => {
  fetchDeptList()
  fetchClassList()
  fetchData()
})
</script>

<style scoped lang="scss">
.student-container {
  .search-form {
    margin-bottom: 20px;
  }
  
  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

// 对话框内容优化
:deep(.el-dialog__body) {
  padding: 20px 30px;
  max-height: 70vh;
  overflow-y: auto;
}

:deep(.el-divider) {
  margin: 20px 0;
  
  .el-divider__text {
    display: flex;
    align-items: center;
    font-size: 14px;
    font-weight: 600;
    color: #409EFF;
  }
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

// 按钮组美化
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

// 单选框样式优化
:deep(.el-radio) {
  margin-right: 25px;
  
  .el-icon {
    margin-right: 4px;
    vertical-align: middle;
  }
}

// 输入框前缀图标样式
:deep(.el-input__prefix) {
  display: flex;
  align-items: center;
}

// 选择框优化
:deep(.el-select-dropdown__item) {
  display: flex;
  align-items: center;
  
  .el-tag {
    min-width: 60px;
    justify-content: center;
  }
}
</style>

